public class LinkListDemo {

    //节点类
    private class ListNode {
        private Object data;
        private ListNode next = null;

        ListNode() {
            data = null;
        }

        ListNode(Object data) {
            this.data = data;
        }
    }

    private ListNode head;//头节点
    private ListNode temp;//临时节点


    //初始化链表，生成一个无数据的头节点
    LinkListDemo() {
        head = new ListNode();
    }
    public void addNode(Object data) {
        ListNode node = new ListNode(data);
        temp = head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = node;

    }
    public int getLength()
    {
        temp = head;
        int length = 0;
        while (temp.next!=null)
        {
            length++;
            temp = temp.next;
        }
        return length;
    }
    public void addNodeByIndex(int index, Object data) {
        if (index < 1 || index > getLength() + 1) {
            System.out.println("插入的位置不合法。");
            return;
        }
        int count = 1; //记录遍历的位置
        ListNode node = new ListNode(data);
        temp = head;
        while (temp.next != null) {
            if (index == count++) {
                node.next = temp.next;
                temp.next = node;
                return;
            }
            temp = temp.next;
        }

    }

}